package Server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import General.ShipQuoterServiceInterface;
import General.ShipmentInterface;
import General.ShipmentIteratorInterface;

public class ShipmentIterator extends UnicastRemoteObject implements ShipmentIteratorInterface {
	
	private static final long serialVersionUID = 1L;
	private SubServerService fSubServers;
	private int fServerNr;
	private int fShipmentNr;
	private boolean fPending;
	
	public ShipmentIterator(SubServerService subServers, boolean pending) throws RemoteException {
		fSubServers = subServers;
		fServerNr = 1;
		fShipmentNr = 1;
		fPending = pending;
	}
	
	public boolean hasNext() throws RemoteException {
		int tempServerNr = fServerNr;
		int tempShipmentNr = fShipmentNr;
		boolean finished = false;
		while (!finished) {
			if (tempServerNr > fSubServers.getNrServers()) {
				return false;
			} else {
				ShipQuoterServiceInterface quoter = fSubServers.getServer(tempServerNr);
				ShipmentInterface shipment;
				if (fPending) {
					shipment = quoter.getPendingShipment(tempShipmentNr);
				} else {
					shipment = quoter.getHistoryShipment(tempShipmentNr);
				}
				if (shipment != null) {
					return true;
				} else {
					tempServerNr++;
					tempShipmentNr = 1;
				}
			}
		}
		return false;
	}
	
	public ShipmentInterface next() throws RemoteException {
		boolean finished = false;
		while (!finished) {
			if (fServerNr > fSubServers.getNrServers()) {
				finished = true;
			} else {
				ShipQuoterServiceInterface quoter = fSubServers.getServer(fServerNr);
				ShipmentInterface shipment;
				if (fPending) {
					shipment = quoter.getPendingShipment(fShipmentNr);
				} else {
					shipment = quoter.getHistoryShipment(fShipmentNr);
				}
				if (shipment != null) {
					fShipmentNr++;
					return shipment;
				} else {
					fServerNr++;
					fShipmentNr = 1;
				}
			}
		}
		return null;
	}
}
